package com.clei.netty.file.client;

import com.clei.netty.decoder.ByteToMsgDecoder;
import com.clei.netty.decoder.HeadTailDecoder;
import com.clei.netty.encoder.MsgToByteEncoder;
import com.clei.utils.PrintUtil;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;

/**
 * file client initializer
 *
 * @author Y
 * @date 2022-04-21
 */
public class FileClientInitializer extends ChannelInitializer<SocketChannel> {

    /**
     * 消息发送者
     */
    private final MsgSender msgSender;

    public FileClientInitializer(MsgSender msgSender) {
        this.msgSender = msgSender;
    }

    @Override
    protected void initChannel(SocketChannel ch) {
        PrintUtil.log("initChannel");
        ChannelPipeline pipeline = ch.pipeline();
        byte head = (byte) 0x7E;
        pipeline.addLast("packetDecoder", new HeadTailDecoder(head, head, true));
        // String 编码解码
        pipeline.addLast("decoder", new ByteToMsgDecoder());
        pipeline.addLast("encoder", new MsgToByteEncoder(head, head));
        pipeline.addLast("handler", new FileClientHandler(this.msgSender));
    }
}
